package com.salesmanager.web.admin.controller.customer;

import com.salesmanager.core.business.customer.model.Customer;

import com.salesmanager.core.business.customer.service.CustomerService;
import com.salesmanager.core.business.generic.exception.ServiceException;
import com.salesmanager.core.business.statistics.model.CustomerStatisticsCriteria;
import com.salesmanager.core.business.statistics.model.StatisticsEntityForCustomer;
import com.salesmanager.core.business.user.model.User;
import com.salesmanager.core.business.user.service.UserService;
import com.salesmanager.web.admin.controller.AbstractController;
import com.salesmanager.web.admin.controller.ControllerConstants;
import com.salesmanager.web.admin.entity.customer.attribute.CustomerModelAttribute;
import com.salesmanager.web.entity.customer.QueryHistoryModelAttribute;
import com.salesmanager.web.model.paging.PaginationDataList;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;

/**
 * Created by Liutong on 2015/12/4.
 */
@Controller
@RequestMapping("/customer")
public class CustomersController extends AbstractController {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/customersInfo", method = RequestMethod.GET)
    public String customersInfo(@ModelAttribute("customerAttribute") CustomerModelAttribute customerAttribute, Model model, HttpServletRequest request) throws ServiceException {
        super.setMenu(model, request, Arrays.asList("customer-report", "customer-info"), "customer-info");
        CustomerStatisticsCriteria criteria = new CustomerStatisticsCriteria();
        //分页
        criteria.setMaxCount(customerAttribute.getPageSize());
        criteria.setStartIndex(customerAttribute.getOffset() - 1);
        //会员id
        if (customerAttribute.getId() != null) {
            criteria.setId(customerAttribute.getId());
        }
        //渠道来源
        if (!StringUtils.isBlank(customerAttribute.getChannel())){
            criteria.setChannel(customerAttribute.getChannel());
        }
        //会员昵称
        if (customerAttribute.getNick() != null && !"".equals(customerAttribute.getNick())) {
            criteria.setNick(customerAttribute.getNick());
        }
        //用户名
        if (customerAttribute.getTelphone() != null && !"".equals(customerAttribute.getTelphone())) {
            criteria.setTelphone(customerAttribute.getTelphone());
        }
        //等级
        if (customerAttribute.getLevel() != null) {
            if (customerAttribute.getLevel() != 0) {
                criteria.setLevel(customerAttribute.getLevel());
            }
        }
        //设备类型
        if (customerAttribute.getDevice() != null && customerAttribute.getDevice() != 0) {
            criteria.setDevice(customerAttribute.getDevice());
        }
        //注册时间
        if (customerAttribute.getStartTime() != null && !"".equals(customerAttribute.getStartTime())) {
            String startTime = customerAttribute.getStartTime();
            startTime = startTime + " 00:00:00";
            criteria.setStartTime(startTime);
        }
        if (customerAttribute.getEndTime() != null && !"".equals(customerAttribute.getEndTime())) {
            String endTime = customerAttribute.getEndTime();
            endTime = endTime + " 23:59:59";
            criteria.setEndTime(endTime);
        }
        //排序
        if (customerAttribute.getSort() != null ) {
            criteria.setSort(customerAttribute.getSort());
        }else {
            criteria.setSort(0);
        }
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();//获取当前用户
        User user=userService.getByUserName(userDetails.getUsername());//获取对象
        if (StringUtils.isNotEmpty(user.getChannelName())){
            criteria.setChannel(user.getChannelName());//设置渠道号
            model.addAttribute("channelNo",user.getChannelName());
        }

        PaginationDataList<StatisticsEntityForCustomer> dataList = customerService.listWithCustomer(criteria);

        model.addAttribute("dataList", dataList);

        if(!"admin".equals(userDetails.getUsername())){
            return ControllerConstants.Tiles.Customer.customersInfoNotAdmin;
        }

        return ControllerConstants.Tiles.Customer.customersInfo;

    }

    @RequestMapping("/customerContactInfo")
    public String customerContactInfo(@ModelAttribute("queryHistory") QueryHistoryModelAttribute queryHistory, Model model, HttpServletRequest request) throws ServiceException {
        super.setMenu(model, request, Arrays.asList("customer-report", "customer-info"), "customer-info");
        String id = request.getParameter("id");
        Long idL = null;
        if (null != id) {
            idL = Long.valueOf(id);
        }
        model.addAttribute("id", id);
        return ControllerConstants.Tiles.Customer.customerContactInfo;
    }

    @RequestMapping("/customerOpLog")
    public String customerOpLog(@ModelAttribute("operateLog") QueryHistoryModelAttribute operateLog, Model model, HttpServletRequest request) throws ServiceException {
        super.setMenu(model, request, Arrays.asList("customer-report", "customer-info"), "customer-info");
        String id = request.getParameter("id");
        Long idL = null;
        if (null != id) {
            idL = Long.valueOf(id);
        }
        model.addAttribute("id", id);
        Customer customer = customerService.getCustomer(idL);
        model.addAttribute("customer", customer);
        return ControllerConstants.Tiles.Customer.customerOperateLog;
    }

    //导出用户电话号码
    @RequestMapping(value = "/exportCustomerPhoneExcel")
    public String exportCustomerPhoneExcel(HttpServletRequest request,HttpServletResponse response) throws ServiceException, IOException {
        CustomerStatisticsCriteria criteria = new CustomerStatisticsCriteria();
        PaginationDataList<StatisticsEntityForCustomer> dataList = customerService.listWithCustomer(criteria);

        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("用户电话号码");
        Row row = sheet.createRow((short) 0);//row 行
        Cell cell = row.createCell(0);//cell 列
        cell.setCellValue("用户电话号码");
        int a=0;//非空行下标
        for (short i = 0; i < dataList.getData().size(); i++) {
            if(StringUtils.isBlank(dataList.getData().get(i).getTelphone())){
                continue;
            }
            a++;
            row = sheet.createRow((short) a);
            cell = row.createCell(0);
            cell.setCellValue(dataList.getData().get(i).getTelphone());

        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            wb.write(os);//转化为字节流
        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);


        Date date = new Date();
        String s = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
      // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+s+ ".xls");

        ServletOutputStream out = response.getOutputStream();//下载

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {

            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);

            byte[] buff = new byte[2048];
            int bytesRead;

            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }

        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return null;
    }

}
